<?
class backup_admin
{
	var $template='control';
	
	function Render()	{
		if($_REQUEST["action"]=='backup') return $this->RenderBackup();
		if($_REQUEST["action"]=='restore') return $this->RenderRestore();
		if($_REQUEST["action"]=='dataset') return $this->RenderDataSetAccess();
		return $this->RenderControl();
		}
	
	function RenderControl() {
		$dao=Array();
		$dao["listtitle"] = GetAdminTitle();
		$dao["controls"] = GetAdminTemplate("backup");
		
		$html_form = TemplaterParse(GetAdminTemplate($this->template),$dao);
		echo RenderAdmin($html_form,$html_list);
		}
	
	function RenderBackup()	{
		$dmp = new Dumper;
		$str = $dmp->backup();
		
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Disposition: attachment; filename=".$_SERVER["HTTP_HOST"].'.'.date('d.m.y').".sql;");
		
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".strlen($str));
		echo $str;
		}
		
	function RenderRestore() {
		$dmp = new Dumper;
		$str = $dmp->restore( ReadContent( $_FILES['userfile']['tmp_name'] ) );
		
		$dao=Array();
		$dao["formtitle"] = GetAdminTitle();
		if($str)
		$dao["controls"] = "<div style='padding:15px;'>Во время восстановления произошла ошибка:<br><span style='color:red;'>".htmlspecialchars($str)."</span></div>";
		else
		$dao["controls"] = "<div style='padding:15px;'>База данных успешно восстановлена.</div>";
		
		$html_form = TemplaterParse(GetAdminTemplate($this->template),$dao);
		echo RenderAdmin($html_form,$html_list);
		}
	
	function RenderDataSetAccess() {
		$dao=Array();
		$dao["formtitle"] = GetAdminTitle();
		$dao["controls"] = "<div style='padding:15px;'>Права на папку data установлены.</div>";
		
		$this->chmod_dir('/data');
		
		$html_form = TemplaterParse(GetAdminTemplate($this->template),$dao);
		echo RenderAdmin($html_form,$html_list);
		}
	
	function chmod_dir($dirname) {
		$handle = opendir($_SERVER['DOCUMENT_ROOT'].$dirname); 
		while (false !== ($file = readdir($handle))) { 
		    if ($file != "." && $file != "..") { 
				@chmod($_SERVER['DOCUMENT_ROOT'].$dirname.'/'.$file,0777);
			    if(is_dir($_SERVER['DOCUMENT_ROOT'].$dirname.'/'.$file)) $this->chmod_dir($dirname.'/'.$file);
		    } 
		}
		closedir($handle); 
		}
}